<template>
    <div class="xtx-city" ref="target">
      <div class="select" @click="toggle" :class="{active: show}">
        <span class="placeholder" v-if="!fullLocation" >{{ placeholder }}</span>
        <span class="value" v-else>{{ fullLocation }}</span>
        <i class="iconfont icon-angle-down"></i>
      </div>
      <div class="option" v-if="show">
        <div v-if="!loading" class="loading"></div>
        <template v-else>
            <span class="ellipsis" v-for="item in currList" :key="item.code" @click="changResult(item)">{{item.name}}</span>
        </template>
        
      </div>
    </div>
  </template>
  <script>
import { computed, ref, reactive } from 'vue'
import { onClickOutside } from '@vueuse/core'
import axios from 'axios'
    export default {
        name: 'XtxCity',
        props: {
            fullLocation: {
                type: String,
                default: '' 
            },
            placeholder: {
              type: String,
              default: '请选择配送地址'
            }
        },
        setup (props, {emit}) {
            const show = ref(false)
            //所有城市数据
            const cityData = ref([])
            const loading = ref(false)
            const open = () => {

                show.value = true
                loading.value = true
                getCityData().then(data => {
                    cityData.value = data
                    loading.value = true
                })
                  // 清空选择结果
                for (const key in changeResult) {
                    changeResult[key] = ''
                }
            }
            const close = () => {
                show.value = false
            }
            const toggle = () => {

                show.value ? close() : open()
            }
            //点击组件外的区域也能实现关闭
            const target = ref(null)
            onClickOutside(target, () => {
                close()
            })
            //计算属性：获取当前显示的地区数据
            const currList = computed (() =>{
                //默认省一级
                let currList  = cityData.value
                //可能：市一级
                if(changeResult.provinceCode && changeResult.provinceName) {
                    currList = currList.find(p => p.code === changeResult.provinceCode ).areaList
                }
                //可能：县地区一级
                if(changeResult.cityCode && changeResult.cityName) {
                    currList = currList.find(p => p.code === changeResult.cityCode).areaList
                }
                return currList 
            })

            //定义选择的省市区县
            const changeResult = reactive({
                provinceCode: '',
                provinceName: '',
                cityCode: '',
                cityName: '',
                countyCode: '',
                countyName: '',
                fullLocation: ''  
            })

            //绑定点击事件，选择不同的省市区
            const changResult = (item) => {
                if(item.level === 0) {
                    changeResult.provinceCode = item.code
                    changeResult.provinceName = item.name
                }
                if(item.level === 1) {
                    changeResult.cityCode = item.code
                    changeResult.cityName = item.name
                }
                if(item.level === 2) {
                    changeResult.countyCode = item.code
                    changeResult.countyName = item.name
                    //最后一级选完了
                    changeResult.fullLocation = `${changeResult.provinceName} ${changeResult.cityName} ${changeResult.countyName}`
                    // 通知父组件改数据
                    emit('change', changeResult)
                    // 关闭
                    close()
                }
            }

            //获取城市数据
            // 1. 数据在哪里？https://yjy-oss-files.oss-cn-zhangjiakou.aliyuncs.com/tuxian/area.json
            // 2. 何时获取？打开城市列表的时候，做个内存中缓存
            // 3. 怎么使用数据？定义计算属性，根据点击的省份城市展示
            const getCityData = () => {
                //这个位置可能有异步操作
                return new Promise((resolve, reject) => {
                    // console.log( user.name ); undefined
                    if(window.cityData) {
                        resolve(window.cityData)
                    } else {
                        //无缓存
                        const url = 'https://yjy-oss-files.oss-cn-zhangjiakou.aliyuncs.com/tuxian/area.json'
                        axios.get(url).then(res => {
                            //缓存
                            window.cityData = res.data
                            resolve(window.cityData)
                        })
                    }
                })
            }
            return {show, toggle, target, loading, currList, changResult}
        }
    }
</script>
  <style scoped lang="less">
  .xtx-city {
    display: inline-block;
    position: relative;
    z-index: 400;  
    .select {
      border: 1px solid #e4e4e4;
      height: 30px;
      padding: 0 5px;
      line-height: 28px;
      cursor: pointer;
      &.active {
        background: #fff;
      }
      .placeholder {
        color: #999;
      }
      .value {
        color: #666;
        font-size: 12px;
      }
      i {
        font-size: 12px;
        margin-left: 5px;
      }
    }
    .option {
      width: 542px;
      border: 1px solid #e4e4e4;
      position: absolute;
      left: 0;
      top: 29px;
      background: #fff;
      min-height: 30px;
      line-height: 30px;
      display: flex;
      flex-wrap: wrap;
      padding: 10px;
      .loading {
      height: 290px;
      width: 100%;
      background: url(../../assets/images/loading.gif) no-repeat center;
    }
      > span {
        width: 130px;
        text-align: center;
        cursor: pointer;
        border-radius: 4px;
        padding: 0 3px;
        &:hover {
          background: #f5f5f5;
        }
      }
    }
  }
  </style>
